package com.xxx.server.controller;

import com.xxx.server.entity.RespBean;
import com.xxx.server.entity.User;
import com.xxx.server.entity.UserLoginParam;
import com.xxx.server.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Api(tags = "LoginController")
@RestController
public class LoginController {

    @Autowired(required = false)
    private IUserService userService;

    //  1、登录
    @ApiOperation(value = "登陆之后返回token")
    @PostMapping(value = "/login")
    public RespBean login(@RequestBody UserLoginParam userLoginParam, HttpServletRequest request){
        //返回用户名、密码和请求
        return userService.login(userLoginParam.getUsername(),userLoginParam.getPassword(),userLoginParam.getCode(),
                request);
    }

    //  2、退出
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        return RespBean.success("退出成功！");
    }

    //  3、获取用户信息
    @ApiOperation(value = "获取当前用户信息")
    @GetMapping("/user/info")
    public User getUserInfo(Principal principal){
        if (null == principal){
            return null;
        }
        String username = principal.getName();  //拿到用户名 从 Principal 中
        User user = userService.getUserByUsername(username);
        user.setPassword(null);     //  密码设置为空
        return user;
    }

}
